/**
 * 封装网络请求
 */
import Vue from 'vue'
import {
	SERVERTAPI
} from '@/config/index.js'
import store from '@/store/index.js'

// 需要修改token，和根据实际修改请求头
export function request(url, data, config) {
	let param = {
		...data
	}
	// 根据请求方法或URL来判断是否添加请求头
	let header = {}
	if (config) {
		header['content-type'] = config
		header['token'] = store.state.token
	} else {
		header['content-type'] = "application/x-www-form-urlencoded"
		header['token'] = store.state.token
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: SERVERTAPI + url,
			method: 'POST',
			header,
			data: param,
			success(response) {
				// 根据返回的状态码做出对应的操作
				if (response.data.code == 1) {
					resolve(response.data)
				} else if (response.data.code == 200) {
					resolve(response.data)
				} else if (response.data.code == 0) {
					uni.$u.toast(response.data.info)
					reject(response.data)
				} else if (response.data.code == 401) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						success(res) {
							if (res.confirm) {
								if(store.state.user.webSocket) store.state.user.webSocket.socketTask.close()
								// webSocket.socketTask.close()
								// store.state.user.webSocket.socketTask.close()
								uni.removeStorageSync('vuex'); // 替换为你要清除的键
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}
						}
					})
				} else if (response.data.code == 402) {
					uni.showModal({
						title: '提示',
						content: '同步数据中,请重新登录',
						success(res) {
							if (res.confirm) {
								if(store.state.user.webSocket) store.state.user.webSocket.socketTask.close()
								uni.removeStorageSync('vuex'); // 替换为你要清除的键
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}
						}
					})
				} else if (response.data.code == 500) {
					uni.$u.toast(response.data.msg)
				}
			},
			fail(err) {
				reject(err);
			},
		});
	}).catch((e) => {
		return Promise.reject(e)
	});
}